"""
Author: runyu.ma

eval_pystr_pass.py
"""

from typing import Dict
from ..core.dslc_parser import String, Identifier, Number, BlockOp
from ..core.dslc_symbol_table import SymbolTable
from ..corefunc import import_pyfile

GLOBAL_EVAL_CNT = 0

def exec_pystr_in_node(stab: SymbolTable, top: String):
    global GLOBAL_EVAL_CNT
    if not isinstance(top, String):
        raise ValueError("not String Node")
    #只处理bare的string
    if not top.parent or isinstance(top.parent, BlockOp):
        GLOBAL_EVAL_CNT += 1
        param = stab.lsvisiable()
        #for k in param:
        #    param[k] = "\'{}\'".format(str(param[k]))
        #print(stab, param, top)
        ret = __exec_pystr(param, top)
        print("eval ---", top, top.parent)
        stab.add("ret_meta_id%d"%GLOBAL_EVAL_CNT, {'ival': ret})
        ret = Identifier("ret_meta_id%d"%GLOBAL_EVAL_CNT)
        ret.parent = top.parent
        return ret
    #普通的string直接返回
    return top


def __exec_pystr(param: Dict[str, str], top: String):
    print('__eval_pystr', top, param, top.value.format_map(param))
    print('eval ---->')
    #这里还是用eval，拿到返回值
    #NOTE:思考要不要换成exec
    print(top.value, param)
    ret = eval(top.value.format_map(param))
    print('----> eend')
    return ret
